package com.fqcar.fqdf.util;

import android.util.Log;

import com.facebook.stetho.server.http.HttpStatus;
import com.fqcar.fqdf.core.volley.OkHttpStack;
import com.fqdf.framework.android.service.downloadservice.DownloadConstans;
import com.fqdf.framework.android.util.CheckLogicUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.Util;
import okio.Buffer;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;

public class DownloadUtil {

    private DownloadUtil() {
        super();
    }

    /**
     * 下载文件
     *
     * @param url
     * @return
     * @throws MalformedURLException
     * @throws IOException
     */
    @Deprecated
    public static InputStream download(String url) throws IOException {
        HttpURLConnection con = (HttpURLConnection) (new URL(url)).openConnection();
//        con.setRequestMethod("POST");
//        con.setDoInput(true);
//        con.setDoOutput(true);
        con.connect();
        return con.getInputStream();
    }

    /**
     * 下载文件到指定文件里面
     *
     * @param downloadUrl 文件网络url
     * @param path        文件保存的地址
     */
    public static DownloadConstans.RESULT downloadFile(String downloadUrl, String path) {
        return downloadFile(downloadUrl, new File(path));
    }

    /**
     * 下载文件到指定文件里面
     *
     * @param downloadUrl 文件网络url
     * @param file        文件保存的地址
     */
    public static DownloadConstans.RESULT downloadFile(String downloadUrl, File file) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            Log.e("DownloadIntent", "can not find saving dir");
            e.printStackTrace();
            return DownloadConstans.RESULT.EXCEPTION;
        }
        InputStream ips = null;
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("GET");
            huc.setReadTimeout(30000);
            huc.setConnectTimeout(30000);
            ips = huc.getInputStream();
            int hand = huc.getResponseCode();
            if (hand == 200) {
                byte[] buffer = new byte[2048];
                int len = 0;
                while ((len = ips.read(buffer)) != -1) {
                    if (fos != null) {
                        fos.write(buffer, 0, len);
                    }
                }
                return DownloadConstans.RESULT.SUCCESS;
            } else {
                Log.e("DownloadIntent", "response code: " + hand);
                return DownloadConstans.RESULT.FAILURE;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return DownloadConstans.RESULT.EXCEPTION;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (ips != null) {
                    ips.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
//                return DownloadConstans.RESULT.EXCEPTION;
            }
        }
    }


    /**
     * 使用okhttp进行下载
     *
     * @param url  url地址
     * @param path 保存的文件path
     * @return 下载成功和失败值
     */
    public static DownloadConstans.RESULT okhttpDownload(String url, String path) {
        if (CheckLogicUtil.isEmpty(url) || CheckLogicUtil.isEmpty(path)) {
            return DownloadConstans.RESULT.PARAMS;
        }
        return okhttpDownload(url, new File(path));
    }

    /**
     * 使用okhttp进行下载
     *
     * @param url  url地址
     * @param file 保存的文件
     * @return 下载成功和失败值
     */
    public static DownloadConstans.RESULT okhttpDownload(String url, File file) {

        if (CheckLogicUtil.isEmpty(url) || file == null) {
            return DownloadConstans.RESULT.PARAMS;
        }

        BufferedSource bufferedSource = null;
        BufferedSink bufferedSink = null;
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            Request request = new Request.Builder().url(url).build();
            Response response = OkHttpStack.getInstance().getOkhttpClient().newCall(request).execute();

            if (response.code() == HttpStatus.HTTP_OK) {

                ResponseBody body = response.body();
                bufferedSource = body.source();
                bufferedSink = Okio.buffer(Okio.sink(file));
                // 注释掉的内容主要为计算相关下载进度，暂时用不到
//                long contentLength = body.contentLength();
                Buffer sinkBuffer = bufferedSink.buffer();
//                long totalBytesRead = 0;
                int bufferSize = 2 * 1024;
                long bytesRead;
                while ((bytesRead = bufferedSource.read(sinkBuffer, bufferSize)) != -1) {
                    sinkBuffer.emit();
//                    totalBytesRead += bytesRead;
//                    int progress = (int) ((totalBytesRead * 100) / contentLength);
                }
                bufferedSink.flush();

                return DownloadConstans.RESULT.SUCCESS;
            } else {
                return DownloadConstans.RESULT.FAILURE;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return DownloadConstans.RESULT.EXCEPTION;
        } catch (IOException e) {
            e.printStackTrace();
            return DownloadConstans.RESULT.EXCEPTION;
        } catch (Exception e) {
            e.printStackTrace();
            return DownloadConstans.RESULT.EXCEPTION;
        } finally {
            Util.closeQuietly(bufferedSink);
            Util.closeQuietly(bufferedSource);
        }


    }

}
